/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.braveo.dict.javadoc;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author jeff.huang
 */
public class DictStorage {
    private static final DictStorage storage = new DictStorage();
    private static final Logger logger = Logger.getLogger(DictStorage.class.getName());

    private final Map<String, List<String>> crossMapping = new HashMap<String, List<String>>();

    private DictStorage(){

    }

    public static DictStorage getStorage(){
        return storage;
    }

    public void addCrossMapping(String key, String value){
        List<String> x = crossMapping.get(key);
        if(x == null){
            x = new LinkedList<String>();
        }
        x.add(value);
        crossMapping.put(key, x);
    }

    public void createContent(String dir, String key, CharSequence content){
        if(dir == null || dir.length() == 0)
            dir = ".";

        String fileName = dir + "/" + key + ".txt";
        
        File file = new File(fileName);
        /*if(file.exists()){
            throw new RuntimeException(fileName);
        }*/
        FileWriter fw = null;
        try{
            fw = new FileWriter(file, true);
            PrintWriter pw = new PrintWriter(fw, true);
            pw.println(content.toString());
            pw.println("<hr>");
        }catch(IOException ioe){
            throw new RuntimeException(ioe);
        }finally{
            if(fw!=null){
                try{
                    fw.close();
                }catch(IOException ioe){
                    
                }
            }
        }
    }

    public void createClassListSql(PrintWriter pw) throws IOException {
        Iterator<String> it = crossMapping.keySet().iterator();
        while (it.hasNext()) {
            String k = it.next();
            logger.info("Key = " + k);
            List<String> vl = crossMapping.get(k);
            StringBuilder sb = new StringBuilder();
            for (String s : vl) {
                sb.append("[").append(s).append("]").append("\n");
            }
            AndroidWord aw = new AndroidWord(k, sb.toString());
            pw.print(AndroidDict.createRecordSql(aw));
            pw.println(";");
        }

    }

    public void createSql(String storageDir, String outputFileName){
        FileWriter fw = null;
        PrintWriter pw = null;
        int linecount = 0;

        try {
            fw = new FileWriter(outputFileName);
            pw = new PrintWriter(fw, true);
            //header
            for (String s : AndroidDict.DATABASE_CREATION) {
                pw.println(s + ";");
            }
            pw.println("begin;");
            //Class list
            createClassListSql(pw);

            //Class Content
            final Pattern p = Pattern.compile("([^ ]+)\\.txt");
            File[] fs = new File(storageDir).listFiles(new FileFilter(){

                public boolean accept(File pathname) {
                    return p.matcher(pathname.getName()).matches();
                }

            });
            for(File f : fs){
                ++linecount;
                if(linecount > 10000){
                    pw.println("COMMIT;");
                    pw.println("BEGIN;");
                    linecount = 0;
                }
                Matcher m = p.matcher(f.getName());
                String clazzName = null;
                if(m.matches()){
                    clazzName = m.group(1);
                }else{
                    throw new RuntimeException(f.getName());
                }
                FileReader fr = null;
                StringBuilder sb = new StringBuilder();
                try{
                    fr = new FileReader(f);
                    BufferedReader br = new BufferedReader(fr);
                    String line;
                    while((line = br.readLine())!=null){
                        sb.append(line);
                        sb.append("\n");
                    }
                }catch(IOException ioe){
                    throw new RuntimeException(ioe);
                }finally{
                    if(fr != null){
                        try{
                            fr.close();
                        }catch(IOException ioe){
                            
                        }
                    }
                }
                AndroidWord aw = new AndroidWord(clazzName, sb.toString());
                String x = AndroidDict.createRecordSql(aw);
                pw.print(x);
                pw.println(";");
            }
            pw.println("commit;");
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (pw != null) {
                    pw.close();
                }
                if (fw != null) {
                    fw.close();
                }
            } catch (IOException ioex) {
            }
        }
    }

    public void clearMemory(){
        crossMapping.clear();
    }


}
